<script setup lang="ts">
  import { ref, reactive, onMounted, defineEmits, watch } from 'vue';
  import {
    getindustry,
    getpolicyIndex,
    getpolicy_direction,
  } from '@/api/dataCenter';
  import useLoading from '@/hooks/loading';
  import { useUserStore } from '@/store';

  // 定义emit事件
  const emit = defineEmits<{
    (e: 'filterChange', params: typeof queryParams): void;
  }>();

  // 接收父组件传递的初始参数
  const props = defineProps<{
    initialParams?: Record<string, any>;
  }>();
  // 触发筛选变更事件
  const triggerFilterChange = () => {
    emit('filterChange', { ...queryParams });
  };
  // 状态管理
  const userStore = useUserStore();
  const { loading, setLoading } = useLoading(true);

  // 筛选条件与接口参数映射对象
  const queryParams = reactive({
    policy_title: '', // 政策标题
    policy_field_id: '', // 领域id
    policy_direction_id: '', // 方向id
    policy_industry_id: '', // 行业id
    province_id: '', // 省份id
    city_id: '', // 城市id
    area_id: '', // 区县id
    create_time_start: '', // 开始时间
    create_time_end: '', // 结束时间
  });

  // 保存初始状态用于重置
  const initialQueryParams = { ...queryParams };

  // 数据源
  const dataSource = reactive({
    industryList: [], // 行业列表
    filedList: [], // 领域列表
    dirctionList: [], // 方向列表
  });

  // 控制各筛选项的展开/折叠状态
  const isExpanded = ref([false, false, false, false]);

  // 核心：监听initialParams变化，合并到queryParams
  watch(
    () => props.initialParams,
    (newParams) => {
      if (newParams) {
        // 关键逻辑：只覆盖newParams中存在的字段，其他字段保持queryParams原有值
        Object.keys(newParams).forEach((key) => {
          // 仅当newParams的键在queryParams中存在时才覆盖（避免注入无效字段）
          if (Object.prototype.hasOwnProperty.call(queryParams, key)) {
            queryParams[key as keyof typeof queryParams] = newParams[key];
          }
        });
        triggerFilterChange();
      }
    },
    { immediate: true, deep: true } // immediate: 初始化时就执行一次
  );

  // 初始化数据
  onMounted(() => {
    Promise.all([
      getindustry({ page_size: 10000 }),
      getpolicyIndex({ page_size: 10000 }),
      getpolicy_direction({ page_size: 10000 }),
    ])
      .then(([allIndustrys, allfieldList, alldirectionList]) => {
        dataSource.industryList = allIndustrys.data.list;
        dataSource.filedList = allfieldList.data.list;
        dataSource.dirctionList = alldirectionList.data.list;
        setLoading(false);
      })
      .catch(() => {
        setLoading(false);
      });
  });

  // 重置所有筛选条件
  const resetAllFilters = () => {
    Object.keys(queryParams).forEach((key) => {
      queryParams[key as keyof typeof queryParams] =
        initialQueryParams[key as keyof typeof queryParams];
    });
    isExpanded.value = [false, false, false, false];
    triggerFilterChange();
  };

  // 处理日期范围选择
  const handleDateChange = (date: any, dateString: string[]) => {
    queryParams.create_time_start = dateString[0] || '';
    queryParams.create_time_end = dateString[1] || '';
    triggerFilterChange();
  };

  // 处理选项点击
  const handleOptionClick = (
    paramKey: keyof typeof queryParams,
    value: string
  ) => {
    queryParams[paramKey] = queryParams[paramKey] === value ? '' : value;
    triggerFilterChange();
  };

  // 处理搜索提交
  const handleSearch = () => {
    triggerFilterChange();
  };
</script>

<template>
  <!-- 高级搜索区域 -->
  <a-row class="heightArea" :loading="loading">
    <!-- 1. 省市地区筛选 -->
    <a-row style="display: flex; width: 100%">
      <a-col :span="1.5" class="bigTile"> 省市地区 </a-col>
      <a-col :span="21" class="heightItme">
        <div class="itemaa">
          <div
            :class="[queryParams.province_id === '' ? 'active' : '']"
            @click="handleOptionClick('province_id', '')"
          >
            全国
          </div>

          <!-- 折叠状态显示部分省份 -->
          <div
            v-for="(item, index) in userStore.allProvice.slice(0, 16)"
            :key="index"
            :class="[queryParams.province_id === item.id ? 'active' : '']"
            @click="handleOptionClick('province_id', item.id)"
          >
            {{ item.name }}
          </div>

          <!-- 展开状态显示剩余省份 -->
          <div
            v-show="isExpanded[0]"
            v-for="(item, index) in userStore.allProvice.slice(16)"
            :key="`expanded-province-${index}`"
            :class="[queryParams.province_id === item.id ? 'active' : '']"
            style="margin-top: 4px"
            @click="handleOptionClick('province_id', item.id)"
          >
            {{ item.name }}
          </div>
        </div>
      </a-col>
      <a-col :span="1.5">
        <div class="more" @click="isExpanded[0] = !isExpanded[0]">
          {{ isExpanded[0] ? '收起' : '更多' }}
          <icon-down v-if="!isExpanded[0]" style="margin-left: 2px" />
          <icon-up v-else style="margin-left: 2px" />
        </div>
      </a-col>
    </a-row>
    <a-divider />

    <!-- 2. 行业筛选 -->
    <a-row style="display: flex; width: 100%">
      <a-col :span="1.5" class="bigTile"> 行业 </a-col>
      <a-col :span="21" class="heightItme">
        <div class="itemaa" v-if="dataSource.industryList.length">
          <div
            :class="[queryParams.policy_industry_id === '' ? 'active' : '']"
            @click="handleOptionClick('policy_industry_id', '')"
          >
            全部
          </div>

          <!-- 折叠状态显示部分行业 -->
          <div
            v-for="(item, index) in dataSource.industryList.slice(0, 12)"
            :key="index"
            :class="[
              queryParams.policy_industry_id === item.industry_id
                ? 'active'
                : '',
            ]"
            @click="handleOptionClick('policy_industry_id', item.industry_id)"
          >
            {{ item.industry_name }}
          </div>

          <!-- 展开状态显示剩余行业 -->
          <div
            v-show="isExpanded[1]"
            v-for="(item, index) in dataSource.industryList.slice(12)"
            :key="`expanded-industry-${index}`"
            :class="[
              queryParams.policy_industry_id === item.industry_id
                ? 'active'
                : '',
            ]"
            style="margin-top: 4px"
            @click="handleOptionClick('policy_industry_id', item.industry_id)"
          >
            {{ item.industry_name }}
          </div>
        </div>
      </a-col>
      <a-col :span="1.5">
        <div class="more" @click="isExpanded[1] = !isExpanded[1]">
          {{ isExpanded[1] ? '收起' : '更多' }}
          <icon-down v-if="!isExpanded[1]" style="margin-left: 2px" />
          <icon-up v-else style="margin-left: 2px" />
        </div>
      </a-col>
    </a-row>
    <a-divider />

    <!-- 3. 领域筛选 -->
    <a-row style="display: flex; width: 100%">
      <a-col :span="1.5" class="bigTile"> 领域 </a-col>
      <a-col :span="21" class="heightItme">
        <div class="itemaa" v-if="dataSource.filedList.length">
          <div
            :class="[queryParams.policy_field_id === '' ? 'active' : '']"
            @click="handleOptionClick('policy_field_id', '')"
          >
            全部
          </div>

          <!-- 折叠状态显示部分领域 -->
          <div
            v-for="(item, index) in dataSource.filedList.slice(0, 10)"
            :key="index"
            :class="[
              queryParams.policy_field_id === item.field_id ? 'active' : '',
            ]"
            @click="handleOptionClick('policy_field_id', item.field_id)"
          >
            {{ item.field_name }}
          </div>

          <!-- 展开状态显示剩余领域 -->
          <div
            v-show="isExpanded[2]"
            v-for="(item, index) in dataSource.filedList.slice(10)"
            :key="`expanded-field-${index}`"
            :class="[
              queryParams.policy_field_id === item.field_id ? 'active' : '',
            ]"
            @click="handleOptionClick('policy_field_id', item.field_id)"
          >
            {{ item.field_name }}
          </div>
        </div>
      </a-col>
      <a-col :span="1.5">
        <div class="more" @click="isExpanded[2] = !isExpanded[2]">
          {{ isExpanded[2] ? '收起' : '更多' }}
          <icon-down v-if="!isExpanded[2]" style="margin-left: 2px" />
          <icon-up v-else style="margin-left: 2px" />
        </div>
      </a-col>
    </a-row>
    <a-divider />

    <!-- 4. 方向筛选 -->
    <a-row style="display: flex; width: 100%">
      <a-col :span="1.5" class="bigTile"> 方向 </a-col>
      <a-col :span="21" class="heightItme">
        <div class="itemaa" v-if="dataSource.dirctionList.length">
          <div
            :class="[queryParams.policy_direction_id === '' ? 'active' : '']"
            @click="handleOptionClick('policy_direction_id', '')"
          >
            全部
          </div>

          <!-- 折叠状态显示部分方向 -->
          <div
            v-for="(item, index) in dataSource.dirctionList.slice(0, 10)"
            :key="index"
            :class="[
              queryParams.policy_direction_id === item.direction_id
                ? 'active'
                : '',
            ]"
            @click="handleOptionClick('policy_direction_id', item.direction_id)"
          >
            {{ item.direction_name }}
          </div>

          <!-- 展开状态显示剩余方向 -->
          <div
            v-show="isExpanded[3]"
            v-for="(item, index) in dataSource.dirctionList.slice(10)"
            :key="`expanded-direction-${index}`"
            :class="[
              queryParams.policy_direction_id === item.direction_id
                ? 'active'
                : '',
            ]"
            @click="handleOptionClick('policy_direction_id', item.direction_id)"
          >
            {{ item.direction_name }}
          </div>
        </div>
      </a-col>
      <a-col :span="1.5">
        <div class="more" @click="isExpanded[3] = !isExpanded[3]">
          {{ isExpanded[3] ? '收起' : '更多' }}
          <icon-down v-if="!isExpanded[3]" style="margin-left: 2px" />
          <icon-up v-else style="margin-left: 2px" />
        </div>
      </a-col>
    </a-row>
    <a-divider />
    <!-- 时间与搜索区域 -->
    <a-row style="height: 25px; width: 100%">
      <a-col :span="17" class="heightItme">
        <div class="bigTile" style="margin-top: 5px"> 发布时间 </div>
        <a-range-picker
          @change="handleDateChange"
          style="width: 254px; margin-top: 0px"
          :value="
            queryParams.create_time_start
              ? [queryParams.create_time_start, queryParams.create_time_end]
              : []
          "
        />
      </a-col>
      <a-col :span="7" class="heightItme">
        <a-space direction="vertical" size="large">
          <a-input-search
            :style="{ width: '320px' }"
            placeholder="请输入政策标题查询"
            search-button
            v-model="queryParams.policy_title"
            @search="handleSearch"
          >
            <template #button-icon>
              <icon-search />
            </template>
            <template #button-default> 搜索 </template>
          </a-input-search>
        </a-space>
        <a-button @click="resetAllFilters" type="dashed"> 重置 </a-button>
      </a-col>
    </a-row>
    <a-divider style="margin-bottom: -10px" />
  </a-row>
</template>

<style scoped lang="less">
  .spinLoading {
    height: 90vh;
    width: 100%;
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: center;
  }

  .heightArea {
    box-sizing: border-box;
    width: 100%;
    padding: 30px;
  }

  .bigTile {
    font-weight: bold;
    color: #333;
    font-size: 15px;
    width: 100px;
    padding-top: 4px;
  }

  .heightItme {
    display: flex;
    flex-direction: row;
    margin-bottom: -20px;
  }

  .itemaa {
    display: flex;
    flex-direction: row;
    align-items: center;
    flex-wrap: wrap;
    padding-bottom: 5px;

    > div {
      border-radius: 4px;
      color: #63656a;
      margin-bottom: 10px;
      cursor: pointer;
      margin-right: 8px;
      padding: 4px 8px;
      white-space: nowrap;
      &:hover {
        color: #3677f6;
      }
    }

    .active {
      background: #3677f6;
      color: #fff;
      &:hover {
        color: #fff;
      }
    }
  }

  .more {
    color: #3677f6;
    margin-top: 4px;
    white-space: nowrap;
    cursor: pointer;
    display: flex;
    align-items: center;
  }

  // 重置按钮样式优化
  ::v-deep .arco-btn-text {
    &:hover {
      color: #3677f6;
      background-color: rgba(54, 119, 246, 0.1);
    }
  }
</style>
